<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--  -->
    <el-card>
      <el-alert show-icon title="注意: 只允许第三级分类设置参数!" type="warning" :closable="false"></el-alert>

      <el-row>
        <el-col class="cat_opt">
          <span>选择商品分类</span>
          <!-- 级联选择器 -->
          <el-cascader
            class="cascader"
            v-model="selsetkeys"
            :options="cateList"
            :props="cateProps"
            @change="handelChange"
            expand-trigger="hover"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs选项卡 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!--  -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            class="addbtntype"
            :disabled="isBtnDisable"
            type="primary"
            @click="addDialogVisible=true"
          >添加参数</el-button>         
          <!-- 动态属性表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable  @close="handleClose(i,scope.row)" :key="i" v-for="(item,i) in scope.row.attr_vals">{{item}}</el-tag>
                <el-input
                  class="addinput"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column lable="参数名称" prop="attr_name"></el-table-column>
            <el-table-column lable="操作">
              <template slot-scope="scope">
                <el-button type="primary" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" @click="delEditDialog(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            class="addbtntype"
            :disabled="isBtnDisable"
            type="primary"
            @click="addDialogVisible=true"
          >添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
            <template slot-scope="scope">
                <el-tag closable  @close="handleClose(i,scope.row)" :key="i" v-for="(item,i) in scope.row.attr_vals">{{item}}</el-tag>
                <el-input
                  class="addinput"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column lable="参数名称" prop="attr_name"></el-table-column>
            <el-table-column lable="操作">
              <template slot-scope="scope">
                <el-button type="primary" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" @click="delEditDialog(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- dialog 添加对话框 -->
    <el-dialog :title="'添加'+ title" :visible.sync="addDialogVisible" width="30%">
      <!-- form表单 -->
      <el-form
        :model="addRuleForm"
        :rules="addRuleFormRules"
        ref="addRuleFormRef"
        label-width="100px"
      >
        <el-form-item :label="title" prop="attr_name">
          <el-input v-model="addRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改'+ title"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClose"
    >
      <!-- form表单 -->
      <el-form
        :model="editRuleForm"
        :rules="editRuleFormRules"
        ref="editRuleFormRef"
        label-width="100px"
      >
        <el-form-item :label="title" prop="attr_name">
          <el-input v-model="editRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      cateList: [],
      // 级联选择框属性
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selsetkeys: [],
      //   tabs选项卡
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      //   dialog
      addDialogVisible: false,
      addRuleForm: {},
      addRuleFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      //   修改对话框
      editDialogVisible: false,
      editRuleForm: {},
      editRuleFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
    //   
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('/categories')
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    // 级联选择框变化会触发
    async handelChange() {
      this.getParamsData()
    },
    // tabs选项卡函数
    handleClick() {
      // console.log(this.activeName);
      this.getParamsData()
    },
    async getParamsData() {
      if (this.selsetkeys.length < 3) {
        return (
            this.selsetkeys = [],
            this.manyTableData = [],
            this.onlyTableData = []
            )
      } else {
        // console.log(this.selsetkeys)
        // 获取动态参数
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: this.activeName } }
        )
        // this.res.data.forEach()
        console.log(res.data)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        if (this.activeName == 'many') {
          this.manyTableData = res.data
        } else {
          this.onlyTableData = res.data
        }
      }
    },
    addParams() {
      this.$refs.addRuleFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return this.$message.error('添加失败,此参数不能为空')
        const { data: res } = await this.$http.post(
          `/categories/${this.cateId}/attributes`,
          {
            attr_name: this.addRuleForm.attr_name,
            attr_sel: this.activeName
          }
        )
        console.log(res)
        if (res.meta.status !== 201)
          return this.$http.$message.error(res.meta.msg)

        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    // 重置表单
    editDialogClose() {
      this.$refs.editRuleFormRef.resetFields()
    },
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `/categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: this.activeName
        }
      )
      // console.log(res);
      this.editRuleForm = res.data
      console.log(this.editRuleForm.attr_name)
      this.editDialogVisible = true
    },

    editParams() {
      this.$refs.editRuleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `/categories/${this.cateId}/attributes/${this.editRuleForm.attr_id}`,
          {
            attr_name: this.editRuleForm.attr_name,
            attr_sel: this.activeName
          }
        )
        console.log(res)
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    async delEditDialog(id) {
      const confirm = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      console.log(confirm)
      if (confirm == 'cancel') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      )
      console.log(res)
      this.getParamsData()
    },
    async handleInputConfirm(row){
        if(row.inputValue.trim().length === 0) {
            row.inputValue = ''
            row.inputVisible = false
            return
        }
        row.attr_vals.push(row.inputValue.trim())
        // const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
        //     attr_name:row.attr_name,
        //     attr_sel:row.attr_sel,
        //     attr_vals:row.attr_vals.join(' ')
        // })
        this.savaArrVals(row)
        // console.log(res);
        
        row.inputValue = ''
        row.inputVisible = false
        
    },
    showInput(row){
        row.inputVisible = true
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        })
    },
    async savaArrVals(row) {
         const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
            attr_name:row.attr_name,
            attr_sel:row.attr_sel,
            attr_vals:row.attr_vals.join(' ')
        })
    },
        // 删除
    handleClose(i,row){
        row.attr_vals.splice(i,1)
        this.savaArrVals(row)

    }
  },
  //   计算属性
  computed: {
    isBtnDisable() {
      if (this.selsetkeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 获取三级id
    cateId() {
      if (this.selsetkeys.length == 3) {
        return this.selsetkeys[2]
      } else {
        return null
      }
    },
    title() {
      if (this.activeName == 'many') {
        return '动态参数'
      } else {
        return '静态参数'
      }
    },

  },
  created() {
    this.getCateList()
  }
}
</script>
<style lang='css' scoped>
.cat_opt {
  margin: 15px 0;
  text-align: left;
}
.cascader {
  /* float: left; */
  margin-left: 20px;
}
.addbtntype {
  float: left;
}
.el-tag {
  margin: 0 5px;
}
.addinput {
    width: 120px;
}
</style>